package com.kfh.ybracelet.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kfh.ybracelet.R;
import com.kfh.ybracelet.base.BaseActivity;
import com.kfh.ybracelet.bean.RegisterToken;
import com.kfh.ybracelet.net.HttpUtil;
import com.kfh.ybracelet.utils.CommonUtils;
import com.kfh.ybracelet.utils.Constant;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 注册页面
 * Created by Aaron on 15/8/3.
 */
public class RegisterActivity extends BaseActivity {

    private EditText et_tel;
    private EditText et_verify_code;
    private EditText et_nickname;
    private TextView tv_get_verify_code;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_register);

//        mApplication.addActivity(this);

        initWidget();

    }

    private void initWidget() {

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);

        tv_get_verify_code = (TextView) findViewById(R.id.tv_get_verify_code);

        tv_title.setText(getResources().getString(R.string.register_user));

        et_tel = (EditText) findViewById(R.id.et_photo);
        et_verify_code = (EditText) findViewById(R.id.et_verify_code);

        et_nickname = (EditText) findViewById(R.id.et_nickname);

        Button btn_next = (Button) findViewById(R.id.btn_next);

        iv_left.setOnClickListener(this);
        tv_get_verify_code.setOnClickListener(this);
        btn_next.setOnClickListener(this);

    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {

            case R.id.iv_left:

                finish();

                break;
            case R.id.tv_get_verify_code: //获取验证码

                if (CommonUtils.isNull(et_tel.getText().toString().trim())) {
                    showToast("请输入手机号码");
                    return;
                }

                //倒计时
                countDown();

                //获取验证码
                getSms();

                break;
            case R.id.btn_next: //下一步

                if (CommonUtils.isNull(et_tel.getText().toString().trim())) {
                    showToast("请输入有效手机号");
                    return;
                }
                if (CommonUtils.isNull(et_verify_code.getText().toString().trim())) {
                    showToast("请输入短信验证码");
                    return;
                }
                if (CommonUtils.isNull(et_nickname.getText().toString().trim())) {
                    showToast("请输入昵称");
                    return;
                }

                //提交验证
                submitConfirm();

////                //提交验证
////                SMSSDK.submitVerificationCode("86", et_tel.getText().toString().trim(), et_verify_code.getText().toString().trim());
//
//                Intent mIntent = new Intent(RegisterActivity.this, InputPswActivity.class);
//                //type 0 是注册 输入密码  1 是忘记密码 重置密码
//                mIntent.putExtra("type", 0);
//                mIntent.putExtra("phone", et_tel.getText().toString().trim());
//                mIntent.putExtra("nickName", et_nickname.getText().toString().trim());
//                mIntent.putExtra("securityCode", et_verify_code.getText().toString().trim());//验证码
//                startActivity(mIntent);

//                register();
                break;

        }
    }


    private void submitConfirm() {

        JSONObject j = new JSONObject();
        j.put("phoneNum", et_tel.getText().toString().trim());
        j.put("nickName", et_nickname.getText().toString().trim());
        j.put("msCode", et_verify_code.getText().toString().trim());

        HttpUtil.setPostRequest("验证中...", this, Constant.WEB_ROOT + Constant.REGISTER, j.toJSONString(),
                getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            RegisterToken resultBaseBean = JSONObject.parseObject(str, RegisterToken.class);
//                            if (Constant.STATUS_SUCCESS == resultBaseBean.code) {

                                Intent intent = new Intent(RegisterActivity.this, RegisterInputActivity.class);
                                intent.putExtra("token", resultBaseBean.token.token);
                                startActivity(intent);

//                            } else {
//                                showToast(Constant.showErrorMsg(resultBaseBean.code, RegisterActivity.this));
//                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            showToast("验证失败");
                        }

                    }
                }, null);

    }

    /**
     * 获取验证码
     */
    private void getSms() {

        JSONObject j = new JSONObject();

        j.put("phoneNum", et_tel.getText().toString().trim());
        j.put("token", sp.getString(Constant.TOKEN, ""));
        j.put("type", "0");

        HttpUtil.setPostRequest("正在获取验证码", this, Constant.WEB_ROOT + Constant.SMSCODE,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            org.json.JSONObject result = new org.json.JSONObject(str);

//                            if (result.getInt("code") == Constant.STATUS_SUCCESS) {

                                showToast("请注意查收验证码");

//                            } else {
//                                showToast(Constant.showErrorMsg(result.getInt("code"), RegisterActivity.this));
//                            }

                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }
                }, null);

//        EventHandler eventHandler = new EventHandler() {
//            public void afterEvent(int event, int result, Object data) {
////                show.dismiss();
//                if (result == SMSSDK.RESULT_COMPLETE) {
//                    //回调完成
//
//                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
//                        //提交验证码验证成功
////                        LogUtil.e("sms", "==========提交验证码成功 =========");
////                        Intent intent = new Intent(RegisterActivity.this, InputPswActivity.class);
////                        intent.putExtra("phone",et_tel.getText().toString().trim());
////                        startActivity(intent);
//
////                        Intent mIntent = new Intent(RegisterActivity.this, InputPswActivity.class);
////                        //type 0 是注册 输入密码  1 是忘记密码 重置密码
////                        mIntent.putExtra("type",0);
////                        mIntent.putExtra("phone",et_tel.getText().toString().trim());
////                        mIntent.putExtra("nickName", et_nickname.getText().toString().trim());
////                        startActivity(mIntent);
//
//                    }else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
//                        //获取验证码成功
//                        LogUtil.e("sms", "==========获取验证码成功 =========");
//                        // 开始计时
////                        runOnUiThread(new Runnable() {
////                            public void run() {
//////                                btn_code.startTickWork();
////                            }
////                        });
//
//                    }else if (event ==SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES){
//                        //返回支持发送验证码的国家列表
//                    }
//                }else{
//                    //验证失败
//                    showToast("验证码错误");
//                }
//            }
//        };
//        // 注册回调监听接口
//        SMSSDK.registerEventHandler(eventHandler);
//        //提交发送短信的请求
//        SMSSDK.getVerificationCode("86", et_tel.getText().toString().trim());
//        ready = true;

    }

    //    boolean ready;
    protected void onDestroy() {
        super.onDestroy();

//        if (ready) {
//            // 销毁回调监听接口
//            SMSSDK.unregisterAllEventHandler();
//        }
        if (executor != null) {
            executor.shutdownNow();
            executor = null;
        }

    }

    /**
     * 倒计时
     */
    private void countDown() {

        tv_get_verify_code.setClickable(false);
        tv_get_verify_code.setEnabled(false);
        if (executor == null) {
            executor = Executors.newSingleThreadExecutor();
        }

        tv_get_verify_code.setText(currentTime + " 秒");
        for (int i = 0; i < 60; i++) {

            executor.execute(new Runnable() {

                @Override
                public void run() {

                    SystemClock.sleep(1000);

                    changeTime();
                }
            });

        }

    }

    int currentTime = 60;
    private ExecutorService executor;

    /**
     * 改变界面时间
     */
    private void changeTime() {
        runOnUiThread(new Runnable() {
            public void run() {

                if (currentTime == 1) {
                    currentTime = 60;
                    tv_get_verify_code.setText(getResources().getString(R.string.get_verify_code));
                    tv_get_verify_code.setClickable(true);
                    tv_get_verify_code.setEnabled(true);

                } else {
                    tv_get_verify_code.setText(--currentTime + " 秒");
                }
            }
        });
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();

        mApplication.cancelPendingRequests(getClass().getName());
    }
}
